package com.netprovider.user.service.baseinfo;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.XMLMessage;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.ls.fw.commons.core.utils.collections.CollectionUtils;

/**
 * 系统全局拦截器（排除登录服务调用）
 * 用于校验登录的账号是否已在别处登录
 * 已在别处登录这抛出异常
 */
public class AuthInterceptor extends AbstractPhaseInterceptor<Message> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public AuthInterceptor() {
        //定义拦截器阶段
        super(Phase.RECEIVE);
    }
    public static Map<String, String> toMap(String url,String flag) {
        Map<String, String> map = null;
        if (StringUtils.isNotBlank(url)) {
            map = new HashMap<String, String>();
             
            String[] arrTemp = url.split(flag);          
            for (String str : arrTemp) {
                String[] qs = str.split("=");
                map.put(qs[0], qs[1]);
            }
        }
        return map;
    }
    /**
     * @Description: 拦截器操作
     * @param message 被拦截到的消息
     * @throws Fault
     */
    @Override
    public void handleMessage(Message message)  {
        logger.info("=====自定义拦截器=======");

        String methodName= getMethod(message);
        //排除拦截的方法
        List<String> list = new ArrayList<String>();
        list.add("login");
        list.add("forgotPassword");
        if(!list.contains(methodName)) {
            Map<String, String> reqParamsMap = new HashMap<String, String>();
            //根据请求方式区分取得GET和POST的参数
            if (message.get(Message.HTTP_REQUEST_METHOD).equals("GET")) {
                //get参数，=&格式
                String reqParams = (String) message.get(Message.QUERY_STRING);
                logger.info("请求的参数：" + reqParams);
                //注:toMap为自定义方法,实现将String转成map
                reqParamsMap = toMap(reqParams, "&");
            } else if (message.get(Message.HTTP_REQUEST_METHOD).equals("POST")) {
                InputStream is = message.getContent(InputStream.class);
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                try {
                    while ((line = in.readLine()) != null) {
                        //post参数，json格式
                        buffer.append(line);
                    }
                    logger.info("请求的参数：" + buffer);
                    JSONObject jasonObject = JSONObject.parseObject(buffer.toString());
                    reqParamsMap = (Map) jasonObject;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (is != null) {
                    //这里一定要加,post参数流读取结束如果不加这个操作,会报io异常
                    message.setContent(InputStream.class, new ByteArrayInputStream(buffer.toString().getBytes()));
                }
            }
            if (reqParamsMap != null) {
                String agentCode = String.valueOf(reqParamsMap.get("agentCode"));
                //注:这里是系统用户登陆唯一标志,使用时自己定义
                String cid = getId();
                if (StringUtils.isNotEmpty(cid)&&
                      !StringUtils.equals(cid, String.valueOf(reqParamsMap.get("cid")))) {
                    throw new Fault(new Exception("已在别处已登录"));
                 }
            }
        }
    }

    /**
     * @Description:handleMessage异常后执行
     * @param message
     */
    @Override
    public void handleFault(Message message) {
        super.handleFault(message);

        logger.info("=================================："+"handleFault");
    }

    /**
     * @Description:取得请求服务的具体方法
     * @param message
     * @return
     */
    private String getMethod(Message message) {
        //通过分析webservice的uri取得实际执行的方法,该webservice使用cxf的RESTFul形式发布
        String requestUri = (String) message.get(XMLMessage.REQUEST_URI);
        String[] methods = StringUtils.split(requestUri,"/");
        logger.debug("********method name:" + requestUri);
        return methods!=null && methods.length>0?methods[methods.length-1]:"";
    }
}